package com.example.demo.datasources;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;

/**
 * 配置多数据源
 */
@Configuration
public class DynamicDataSourceConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.druid.first")
    public DataSource firstDataSource() {
        return DruidDataSourceBuilder.create().build();
    }
    /**
     * 这个事务无效
     * @param dataSource
     * @return
     */
    @Bean(name = "firstDataSourceTransactionManager")
    public DataSourceTransactionManager firstDataSourceTransactionManager(@Qualifier("firstDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
 

    @Bean
    @ConfigurationProperties("spring.datasource.druid.second")
    public DataSource secondDataSource() {
        return DruidDataSourceBuilder.create().build();
    }
    /**
     * 这个事务无效
     * @param dataSource
     * @return
     */
    @Bean(name = "secondDataSourceTransactionManager")
    public DataSourceTransactionManager secondDataSourceTransactionManager(@Qualifier("secondDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
    
    @Bean
    @ConfigurationProperties("spring.datasource.druid.third")
    public DataSource thirdDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.fourth")
    public DataSource fourthDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource,
                                        DataSource thirdDataSource, DataSource fourthDataSource) {
        Map<Object, Object> sources = new HashMap<>();
        sources.put(DataSourceNames.USER, firstDataSource);
        sources.put(DataSourceNames.PROJECT, secondDataSource);
        sources.put(DataSourceNames.IM, thirdDataSource);
        sources.put(DataSourceNames.PAY, fourthDataSource);
        return new DynamicDataSource(firstDataSource, sources);
    }
    
    
 // 配置事物管理器
    /**
             * 这个事务有无效
     * @param dataSource
     * @return
     */
	  @Bean(name="transactionManager") public DataSourceTransactionManager
	   transactionManager(){ return new
	  DataSourceTransactionManager(dataSource(firstDataSource(),secondDataSource(),
	   thirdDataSource(),fourthDataSource())); }
	    

}
